package net.recursv.motific.atweaver
/**
 * Created by: recursv
 * Date: 14/08/2009
 * Time: 12:49:04 PM
 */

public class CanvasTransformer {


  static boolean isCanvas(String content) {
    return content =~ /extends Canvas/
  }

  static String transform(String s) {
    s = addImports(s)
    s = replaceDisplaySetters(s)
    s = replaceCanvasReferences(s)
    if (isCanvas(s)) {
      s = implementInterface(s)
      s = replaceRepaint(s)
    }
    return s
  }

  static String replaceDisplaySetters(String s) {
    return s.replaceAll(/Display\.getDisplay\(\w[\w\d_]*\)\.setCurrent\((\w[\w\d_]*)\);/, {a, b -> "__display = " + b + ";"})
  }

  static String addImports(String content) {
    return content.replaceAll(/package\s*[\w\.]+\s*;/, {it + imports.join()})
  }

  static String[] imports = [
          "import net.recursv.motific.at.scene.GraphicsWrapper;"
  ]

  static String implementInterface(String content) {
    return content.replaceAll(/protected\svoid\spaint\(Graphics \w[\w\d_]*\)\s\{/, "public void doPaint(GraphicsWrapper g) {").replaceAll(/(public\s*)?class\s*(\w[\w\d_]+)\s*extends\s*Canvas\s*(implements \w[\w\d_]*)?\s*\{/, {a, b, c, d ->
      String ret = "";
      if (b != null)
        ret += b;
      if (c != null)
        ret += "class " + c + " extends Canvas "
      if (d == null)
        ret += "implements __Canvas {" else
        ret += d + ", __Canvas {"
      ret += ifaceMethods.join()
      return ret;
    })
  }

  static String[] ifaceMethods = [
          "public void doKeyPress(int keyCode) {keyPressed(keyCode);}",
          "public void doKeyRelease(int keyCode) {keyReleased(keyCode);}",
          "protected void paint(Graphics g) {}"
  ]

  static java.lang.String replaceRepaint(String s) {
    return s.replaceAll(/([\s;{}])(this\.)?repaint\(\);/, {a, b, c -> b + "AtMidlet.repaint();"})
  }

  static String replaceCanvasReferences(String s) {
    return s.replaceAll(/([^\w])Canvas([^\.])/, {a, b, c -> b + "__Canvas" + c}).replaceAll("extends __Canvas", "extends Canvas");
  }
}
